package ml.uuku.oschub.adpater;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import ml.uuku.oschub.R;
import ml.uuku.oschub.widget.PagerSlidingTabStrip;

import java.util.ArrayList;

/**
 * @author <a href=http://my.oschina.net/uuku>uuku</a>
 * @version V0.1
 */
public class ViewPageFragmentAdapter extends FragmentStatePagerAdapter {

    private Context mContext;
    private final PagerSlidingTabStrip mTabStrip;
    private final ViewPager mViewPager;
    private final ArrayList<ViewPagerInfo> mTabs;

    public ViewPageFragmentAdapter(FragmentManager fm, PagerSlidingTabStrip tabStrip, ViewPager viewPager) {
        super(fm);
        this.mContext = viewPager.getContext();
        this.mTabStrip = tabStrip;
        this.mViewPager = viewPager;
        this.mTabStrip.setViewPager(this.mViewPager);
        mTabs = new ArrayList<ViewPagerInfo>();

        this.mViewPager.setAdapter(this);

    }

    public void addTab(String tag, String title, Class<?> clz, Bundle args) {
        ViewPagerInfo tab = new ViewPagerInfo(tag, title, clz, args);
        addFragment(tab);
    }

    public void addFragment(ViewPagerInfo tab) {
        if (tab == null)
            return;
        View tabLayout = View.inflate(mContext, R.layout.base_viewpage_fragment_tab_item, null);
        TextView tabTile = (TextView) tabLayout.findViewById(R.id.tab_title);
        tabTile.setText(tab.title);
        mTabStrip.addTab(tabLayout);
        mTabs.add(tab);
        notifyDataSetChanged();
    }

    @Override
    public Fragment getItem(int position) {
        ViewPagerInfo tab = mTabs.get(position);
        return Fragment.instantiate(mContext, tab.clazz.getName(), tab.args);
    }

    @Override
    public int getCount() {
        return mTabs.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTabs.get(position).title;
    }
}
